#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import aiohttp_jinja2
from aiohttp import web
from aioweb import corelib

import db


routes = web.RouteTableDef()
module_name = 'demo'

@routes.get('/demo')
@corelib.template('demo.html')
async def demo_index(request):
    return {}


@routes.get('/%s/test' % module_name)
async def testget(request):
    params = await corelib.parse_param(request)
    logging.info('-' * 65)
    logging.info('parmas: %s' % params)
    logging.info('-' * 65)
    return web.json_response({'code': 0, 'msg': params})


@routes.get('/%s/users' % module_name)
async def testUser(request):
    session = db.create_session()
    items = [item.single_to_dict() for item in  session.query(db.User)]
    logging.info('-' * 65)
    logging.info('items: %s' % items)
    logging.info('-' * 65)
    return web.json_response({'code': 0, 'msg': items})


async def parse_param(request):
    params = {}
    if request.method == 'POST':
        if not request.content_type:
            raise web.HTTPBadRequest('Missing Content-Type.')
        ct = request.content_type.lower()
        if ct.startswith('application/json'):
            params = await request.json()
            if not isinstance(params, dict) and not isinstance(params, list):
                raise web.HTTPBadRequest('JSON body must be object.')
        else:
            post = await request.post()
            for k, v in post.items():
                params[k] = v
    if request.method == 'GET':
        for k, v in request.query.items():
            params[k] = v
    return params
